package com.shunwang.query_sql.nl2Sql.controller;

import com.shunwang.query_sql.nl2Sql.service.Nl2SqlService;
import com.shunwang.query_sql.tool.api.R;
import com.shunwang.query_sql.tool.util.SqlValidationUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collections;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/api/nl2sql")
@Tag(name = "SQL查询语句接口", description = "SQL查询语句查询功能")
@Validated
public class Nl2SqlController {

    @Autowired
    private Nl2SqlService nl2SqlService;

    @PostMapping("/executeSql")
    @Operation(summary = "执行SQL查询语句", description = "将SQL语句执行查询，返回结果集")
    public R<List<Map<String, Object>>> executeSql(@RequestBody Map<String, String> request) {

        String sql = request.get("sql");
        String naturalLanguage = request.get("query");
        // 参数校验
        if (!StringUtils.hasText(sql)) {
            log.warn("接收到空查询请求");
            return R.fail("查询语句不能为空");
        }

        if (StringUtils.hasText(naturalLanguage)) {
            log.info("用户输入的自然语言: 【{}】,SQL查询语句:【{}】", naturalLanguage, sql);
        } else {
            log.info("SQL查询语句: 【{}】", sql);
        }

        try {
            // SQL安全验证
            try {
                sql = SqlValidationUtil.filterSql(sql);
                SqlValidationUtil.validateSql(sql);
            } catch (IllegalArgumentException e) {
                log.warn("SQL验证失败: {}, SQL: {}", e.getMessage(), sql);
                return R.fail(e.getMessage());
            }

            // 调用服务执行查询
            long startTime = System.currentTimeMillis();
            List<Map<String, Object>> result = nl2SqlService.processQuery(sql);
            long endTime = System.currentTimeMillis();

            // 记录执行时间
            log.info("查询执行完成，耗时: {}ms, 结果集大小: {}", (endTime - startTime),
                    result != null ? result.size() : 0);

            // 处理空结果情况
            if (result == null || result.isEmpty()) {
                return R.data(Collections.emptyList(), "查询成功，但未找到匹配数据");
            }

            return R.data(result, "查询成功");
        } catch (IllegalArgumentException e) {
            log.warn("查询参数异常: {}, SQL: {}", e.getMessage(), sql);
            return R.fail("查询参数错误: " + e.getMessage());
        } catch (RuntimeException e) {
            log.error("查询执行异常: {}, SQL: {}", e.getMessage(), sql, e);
            return R.fail("查询执行失败: " + e.getMessage());
        } catch (Exception e) {
            log.error("查询未知异常: {}, SQL: {}", e.getMessage(), sql, e);
            return R.fail("系统异常，请联系管理员");
        }
    }
}